package cn.wzy.filter;

import cn.wzy.common.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author nihaowzy
 * @date 2020/12/26 21:39
 * 登录拦截
 */

/**
 * 只拦截 .do 的请求和 .jsp后缀的jsp文件
 * @author nihaowzy
 */
@WebFilter(value = {"*.do","*.jsp"})
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取session对象
        HttpSession session = request.getSession();
        //获取session对象中存储的登录用户
        Object user = session.getAttribute(Constant.CURRENT_USER_KEY);
        //user不为空 说明登陆了
        if (user != null){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取登录资源
        //获取请求登录的资源 例如验证码 css文件 js文件等等
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("index.jsp") || requestURI.endsWith("checkCode.do") || requestURI.endsWith("redirect.jsp")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
        //是否是处理登录请求
        String service = request.getParameter("service");
        if (requestURI.endsWith("user.do")&& "login".equals(service)){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }


    }

    @Override
    public void destroy() {

    }
}
